<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class syncSignData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:sign';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步考勤数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $lastDay = date('Y-m-d', strtotime('-1 day'));

        $this->info('- '.$lastDay);
        Storage::append('SyncSign.log', 'Date: '.$lastDay);
        Storage::append('SyncSign.log', 'DateTime: '.date('Y-m-d H:i:s'));
        $sign = Http::get('http://117.34.118.31:8101/api/drv/sign/list', [
            'date' => $lastDay,
        ]);
        $data = $sign->json();
        $code = $data['code'];
        if ($code === 200) {
            $insertData = [];
            foreach ($data['data'] as $k => $v) {
                $insertData[] = [
                    'line'              => $v['lineName'],
                    'license_plate_num' => str_replace('陕G', '', $v['busNum']),
                    'driver'            => str_replace(' ', '', $v['drvName']),
                    'driver_card_num'   => $v['drvCardNum'],
                    'self_numbering'    => $v['busCode'],
                    'actual_sign_time'  => $v['signTime'],
                    'created_at'        => date('Y-m-d H:i:s'),
                ];
            }
            $result = DB::table('akbus_attendance')->insert($insertData);
            if ($result) {
                $this->info('- Insert Success'.PHP_EOL);
                Storage::append('SyncSign.log', 'Result: Insert Success');
            } else {
                $this->info('- Insert Failure'.PHP_EOL);
                Storage::append('SyncSign.log', 'Result: Insert Failure');
            }
        } else {
            $this->info('- Get Failure Code: '.$code.' Msg: '.$data['msg'].PHP_EOL);
            Storage::append('SyncSign.log', 'Result: Get Failure, Code: '.$code.', Msg: '.$data['msg']);
        }
    }
}
